package com.blackhorse.predicates;

import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

/**
 * 自定义gateway路由断言工厂类
 * 1.名字以XXXXRoutePredicateFactory结尾
 * 2.必须继承AbstractRoutePredicateFactory，泛型指定一个配置类
 */
@Component
public class AgeRoutePredicateFactory extends AbstractRoutePredicateFactory<AgeRoutePredicateFactory.Config> {

    public AgeRoutePredicateFactory() {
        super(AgeRoutePredicateFactory.Config.class);
    }

    /**
     * 读取配置文件中的对应参数，赋值到配置类的属性中
     */
    @Override
    public List<String> shortcutFieldOrder() {
        //返回参数顺序必须与配置文件中顺序一致
        return Arrays.asList("minAge", "maxAge");
    }

    @Override
    public Predicate<ServerWebExchange> apply(AgeRoutePredicateFactory.Config config) {
        //断言逻辑
        return serverWebExchange -> {
            //1.接收请求传入的age参数（webflux api）
            String ageStr = serverWebExchange.getRequest().getQueryParams().getFirst("age");
            //2.age为空，断言失败
            if (StringUtils.isBlank(ageStr) || !StringUtils.isNumeric(ageStr)) {
                return false;
            }

            //3.age不为空，进行逻辑判断
            int age = Integer.parseInt(ageStr);
            return age >= config.getMinAge() && age <= config.getMaxAge();
        };
    }

    /**
     * 配置类，用于接收配置危机中的对应参数
     */
    @Data
    @NoArgsConstructor
    public static class Config {
        private int minAge; //18

        private int maxAge; //60
    }
}